﻿import re, logging
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api import mail
from google.appengine.api import urlfetch

import models

# ##########################################################################################################################
def fs(onestr):
    return unicode(onestr, 'utf-8')

def converFromGB2312ToUTF8(onestr):
    newstr = onestr
    try:
        newstr = unicode(newstr, 'cp936', 'ignore')
    except:
        pass
    return newstr.encode('utf-8', 'ignore')

def getContent(url, method=urlfetch.GET, data=None):
    count = 1;
    while(count <= 3):
        response = None
        try:
            #urlfetch.REDIRECT_STATUSES = frozenset([httplib.SEE_OTHER])
            response = urlfetch.fetch(url=url, follow_redirects=False, method=method, payload=data)
            
            redirect_counts = 0
            while redirect_counts < 3 and response and response.status_code in [301,302]:
                logging.info(str(count)+"--"+url+", status_code:"+str(response.status_code))
                if response.headers.has_key('location'):
                    url = response.headers['location']
                elif response.headers.has_key('Location'):
                    url = response.headers['Location']
                else:
                    raise Exception('Could not find location in headers: %r' % (response.headers,))
                global smthhost
                url = smthhost + '/' +url
                #logging.info("new url:"+url)
                response = urlfetch.fetch(url=url, follow_redirects=False)
                redirect_counts += 1

        except:
            logging.info(str(count)+"--"+url+". Error!")
            logging.info(traceback.format_exc())
            count = count + 1
            continue
        logging.info(str(count)+"--"+url+", status_code:"+str(response.status_code))
        if response and response.status_code==200:
            return converFromGB2312ToUTF8(response.content)
        count = count + 1

# ##################################################################################################
def addSong():
    song = models.Song()
    #song.
    return

# ##################################################################################################
def addSongTasteSong(user, songtaste_id, title, artist, url):
    song = models.SongTasteSong(user=user, songtaste_id=songtaste_id, title=fs(title), artist=fs(artist), url=fs(url))
    song.put()
    return song

# ##################################################################################################
def songtasteSongs(user, count=500, offset=0):
    songs = models.SongTasteSong.all().filter('user =', user).order('-created_at').fetch(limit=count, offset=offset)
    return songs

# ##################################################################################################
def delSongtasteSongs(user, count=50, offset=0):
    songs = models.SongTasteSong.all().filter('user =', user).order('-created_at').fetch(limit=count, offset=offset)
    count = 0
    if songs:
        count = len(songs)
    db.delete(songs)
    return count

# ##################################################################################################
def getSongTasteSong(songtaste_id):
    songtaste_url = "http://songtaste.com/play.php?song_id="+str(songtaste_id)
    re_str = '''WrtSongLine\("(\d+)", "(.*?)\s*", "(.*?)\s*", "\d*", "\d*", "(.*?)"\);'''
    htmlcontent = getContent(songtaste_url)
    match_obj = re.search(re_str, htmlcontent)
    
    if not match_obj:
        return None, None, None, None

    song_id = match_obj.group(1).strip()
    song_title = match_obj.group(2).strip()
    song_artist = match_obj.group(3).strip()
    song_url = match_obj.group(4).strip()
    
    return song_id, song_title, song_artist, song_url
    
    